<template>
  <div class="map-container">
    <div class="map-header">
      <h1 class="text-2xl font-bold text-gray-800">地图导航</h1>
      <p class="text-gray-600">查看当前位置和周边信息</p>
    </div>
    
    <div class="map-wrapper">
      <div id="map-container" class="map-content"></div>
      
      <div class="map-controls">
        <button 
          @click="getCurrentLocation" 
          class="location-btn"
          :disabled="loading"
        >
          <i class="fa fa-location-arrow mr-2"></i>
          {{ loading ? '定位中...' : '定位当前位置' }}
        </button>
        
        <div v-if="error" class="error-message">
          <i class="fa fa-exclamation-triangle mr-2"></i>
          {{ error }}
        </div>
        
        <div class="location-info" v-if="currentLocation">
          <h3 class="text-lg font-semibold mb-2">当前位置</h3>
          <p class="text-sm text-gray-600 mb-2">{{ currentLocation.address }}</p>
          <div class="location-details">
            <div class="detail-row">
              <span class="detail-label">经度:</span>
              <span class="detail-value">{{ currentLocation.lng.toFixed(6) }}</span>
            </div>
            <div class="detail-row">
              <span class="detail-label">纬度:</span>
              <span class="detail-value">{{ currentLocation.lat.toFixed(6) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue';

interface Location {
  lng: number;
  lat: number;
  address: string;
}

const map = ref<any>(null);
const marker = ref<any>(null);
const currentLocation = ref<Location | null>(null);
const loading = ref(false);
const error = ref<string | null>(null);

// 高德地图配置
const AMAP_KEY = 'ea14acfbeff3ab37b1a0ac893135a7e8';

// 初始化地图
const initMap = () => {
  if (process.client && window.AMap) {
    map.value = new window.AMap.Map('map-container', {
      zoom: 15,
      center: [116.397428, 39.90923], // 默认北京
      mapStyle: 'amap://styles/normal'
    });
    
    // 添加地图控件
    try {
      if (window.AMap.Scale) {
        map.value.addControl(new window.AMap.Scale());
      }
      if (window.AMap.ToolBar) {
        map.value.addControl(new window.AMap.ToolBar());
      }
    } catch (err) {
      console.warn('地图控件加载失败:', err);
    }
  }
};

// 获取当前位置
const getCurrentLocation = async () => {
  if (!process.client) return;
  
  loading.value = true;
  error.value = null;
  
  try {
    const position = await new Promise<GeolocationPosition>((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject, {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 60000
      });
    });
    
    const { longitude, latitude } = position.coords;
    
    // 获取地址信息
    const address = await getAddressFromCoords(longitude, latitude);
    
    currentLocation.value = {
      lng: longitude,
      lat: latitude,
      address
    };
    
    // 更新地图
    updateMapLocation(longitude, latitude);
    
  } catch (err) {
    console.error('获取位置失败:', err);
    error.value = '无法获取当前位置，请检查定位权限';
  } finally {
    loading.value = false;
  }
};

// 根据坐标获取地址
const getAddressFromCoords = async (lng: number, lat: number): Promise<string> => {
  try {
    const response = await fetch(
      `https://restapi.amap.com/v3/geocode/regeo?key=${AMAP_KEY}&location=${lng},${lat}&output=json`
    );
    const data = await response.json();
    
    if (data.status === '1' && data.regeocode) {
      return data.regeocode.formatted_address || '未知地址';
    } else {
      return '未知地址';
    }
  } catch (err) {
    console.error('获取地址失败:', err);
    return '未知地址';
  }
};

// 更新地图位置和标记
const updateMapLocation = (lng: number, lat: number) => {
  if (!map.value) return;
  
  // 移除旧标记
  if (marker.value) {
    map.value.remove(marker.value);
  }
  
  // 添加新标记
  try {
    marker.value = new window.AMap.Marker({
      position: [lng, lat],
      title: '当前位置'
    });
    
    map.value.add(marker.value);
    map.value.setCenter([lng, lat]);
    
    // 添加信息窗体
    if (window.AMap.InfoWindow) {
      const infoWindow = new window.AMap.InfoWindow({
        content: `
          <div style="padding: 15px; min-width: 200px;">
            <h4 style="margin: 0 0 8px 0; color: #333; font-size: 16px;">
              <i class="fa fa-map-marker" style="color: #1890ff; margin-right: 5px;"></i>
              当前位置
            </h4>
            <p style="margin: 0 0 10px 0; color: #666; font-size: 14px; line-height: 1.4;">
              ${currentLocation.value?.address || '未知地址'}
            </p>
            <div style="border-top: 1px solid #eee; padding-top: 8px; font-size: 12px; color: #999;">
              <div>经度: ${lng.toFixed(6)}</div>
              <div>纬度: ${lat.toFixed(6)}</div>
            </div>
          </div>
        `,
        offset: new window.AMap.Pixel(0, -30)
      });
      
      marker.value.on('click', () => {
        infoWindow.open(map.value, marker.value.getPosition());
      });
    }
  } catch (err) {
    console.warn('地图标记创建失败:', err);
  }
};

// 加载高德地图SDK
const loadAMapSDK = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (process.client && !window.AMap) {
      const script = document.createElement('script');
      script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}&plugin=AMap.Scale,AMap.ToolBar`;
      script.onload = () => resolve();
      script.onerror = () => reject(new Error('Failed to load AMap SDK'));
      document.head.appendChild(script);
    } else {
      resolve();
    }
  });
};

// 页面挂载后初始化
onMounted(async () => {
  try {
    await loadAMapSDK();
    initMap();
    // 自动获取当前位置
    await getCurrentLocation();
  } catch (err) {
    console.error('地图初始化失败:', err);
    error.value = '地图加载失败';
  }
});

// 页面卸载时清理
onUnmounted(() => {
  if (map.value) {
    map.value.destroy();
  }
});
</script>

<style scoped>
.map-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.map-header {
  background: white;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.map-wrapper {
  display: flex;
  height: calc(100vh - 120px);
}

.map-content {
  flex: 1;
  height: 100%;
  background: #e0e0e0;
}

.map-controls {
  width: 300px;
  background: white;
  padding: 20px;
  box-shadow: -2px 0 4px rgba(0,0,0,0.1);
  overflow-y: auto;
}

.location-btn {
  width: 100%;
  padding: 12px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-bottom: 20px;
}

.location-btn:hover:not(:disabled) {
  background: #40a9ff;
}

.location-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.error-message {
  background: #fff2f0;
  border: 1px solid #ffccc7;
  color: #cf1322;
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 20px;
  font-size: 14px;
}

.location-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #1890ff;
}

.location-details {
  margin-top: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #1890ff;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: #666;
  font-weight: 500;
}

.detail-value {
  color: #333;
  font-weight: 600;
  font-family: 'Courier New', monospace;
}

@media (max-width: 768px) {
  .map-wrapper {
    flex-direction: column;
    height: calc(100vh - 160px);
  }
  
  .map-content {
    height: 60%;
  }
  
  .map-controls {
    width: 100%;
    height: 40%;
  }
}
</style> 